import { reqCartList, reqCheckCart, reqDeleteCart, reqAddCart } from '../../apis/cart.js'
import Dialog from '@vant/weapp/dialog/dialog';
import debounce from 'lodash.debounce';
// pages/shopcart/shopcart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    totalPrice: 0,
    totalCount: 0,
    allChecked: false
  },
  onShow() {
    const token = wx.getStorageSync('token')
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }
    this.getShopCartList()
  },

  // 防抖
  updateCount: debounce(async function (e) {
     // 更改购物车数量
    const { goodsid } = e.currentTarget.dataset
    const oldValue = e.currentTarget.dataset.oldvalue
    const count = e.detail - oldValue
    if (count != 0) {
      const res = await reqAddCart(goodsid, count)
      if (res.code == 200) {
        this.getShopCartList()
      }
    }
  }, 1000),

  // 删除购物车商品
  deleteItem(e) {
    const { goodsid } = e.currentTarget.dataset
    Dialog.confirm({
      title: '提示',
      message: '确认要删除吗?',
    })
      .then(async () => {
        // on confirm
        const res = await reqDeleteCart(goodsid)
        if (res.code === 200) {
          // 成功删除重新获取购物车列表数据
          this.getShopCartList()
        }
      })
      .catch(() => {
        // on cancel
        console.log(2222)
      });
  },
  // 获取购物车列表数据
  async getShopCartList() {
    const res = await reqCartList()
    if (res.code === 200) {
      this.setData({
        cartList: res.data
      })
    }
    // 计算总价
    this.getTotalPrice()
    // 计算总数量
    this.getTotalCount()
    // 判断是否全选
    this.isAllChecked()
  },

  // 计算总价
  getTotalPrice() {
    const totalPrice = this.data.cartList.reduce((prev, next) => {
      if (next.isChecked) {
        prev += next.price * next.count
      }
      return prev
    }, 0)
    this.setData({
      totalPrice
    })
  },

  // 计算总数量
  getTotalCount() {
    const totalCount = this.data.cartList.reduce((prev, next) => {
      if (next.isChecked) {
        prev += next.count
      }
      return prev
    }, 0)
    this.setData({
      totalCount
    })
  },

  // 判断是否全选
  isAllChecked() {
    const allChecked = this.data.cartList.every(item => item.isChecked)
      && this.data.cartList.length > 0
    this.setData({
      allChecked
    })
  },

  // 选中商品与取消选中
  async updateChecked(e) {
    const { goodsid } = e.currentTarget.dataset
    const isChecked = e.detail ? 1 : 0
    try {
      const res = await reqCheckCart(goodsid, isChecked)
      if (res.code === 200) {
        // 重新获取购物车列表数据
        await this.getShopCartList()
      }
    } catch (error) {
    }
  }

})